/*
 * Copyright (c) 2006-2021, RT-Thread Development Team
 *
 * SPDX-License-Identifier: Apache-2.0
 *
 * Change Logs:
 * Date           Author       Notes
 * 2021-11-10     zzzlion       the first version
 */
#include "ModbusSystem.h"
#include "jsonrpc/icore.h"
#define PR_BEGIN_EXTERN_C \
    extern "C"            \
    {
#define PR_END_EXTERN_C }
#include "user_mb_app.h"

extern USHORT usSRegHoldBuf[S_REG_HOLDING_NREGS];
extern USHORT usMRegHoldBuf[];
extern unsigned char ucMDiscInBuf[];
extern unsigned char ucMCoilBuf[];
Icore *ModbusSystem::icore4 = nullptr;
static ModbusSystem *modbusSystem_rt;

ModbusSystem::ModbusSystem(Icore *main)
{
    icore4 = main;
    FunName = "ModbusSystem";
    entry = ModbusSystem_thread_entry;
    init("ModbusSystem", 20);

    icore4->parma = (Icore::Parma *)usSRegHoldBuf;
    modbusSystem_rt = this;
}

ModbusSystem::~ModbusSystem()
{
}

/**
 * @brief Use Modbus read position data (PosL and PosH) from FSMC and store it in system parameters.
 * （使用Modbus总线从FSMC中读取位置数据（PosL和PosH），并将其存储在系统参数中）
 * @param parameter
 */
void ModbusSystem_cyc_entry(void *parameter)
{
    while (1)
    {
        unsigned short int data;
        modbusSystem_rt->icore4->sram->fsmc->readFsmc(110, &data);
        modbusSystem_rt->icore4->parma->PosL = data;
        modbusSystem_rt->icore4->sram->fsmc->readFsmc(111, &data);
        modbusSystem_rt->icore4->parma->PosH = data;

        rt_thread_mdelay(200);
    }
}

void ModbusSystem::ModbusSystem_thread_entry(void *parameter)
{
    rt_thread_t tid1 = RT_NULL;
    tid1 = rt_thread_create("ModbusSystem_cyc", ModbusSystem_cyc_entry, RT_NULL, 1024, 20, 10);
    if (tid1 != RT_NULL)
    {
        rt_thread_startup(tid1);
    }
    modbusSystem_rt->handle((rt_mq_t)parameter);
}
